package com.hbzhit.config;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.config.MagicDynamicDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * MagicApi多数据源配置
 * @author DING
 * @date 2020/12/15 14:44
 * @version 1.0
 **/
@Configuration
@AllArgsConstructor
public class MagicApiConfig {
    private final DynamicDataSourceProperties dynamicDataSourceProperties;
    private final DataSourceCreator dataSourceCreator;

    @Bean
    public MagicDynamicDataSource magicDynamicDataSource(){
        MagicDynamicDataSource dynamicDataSource = new MagicDynamicDataSource();

        // 获取 dynamic datasource 配置多数据源
        Map<String, DataSourceProperty> dsMap = dynamicDataSourceProperties.getDatasource();
        dsMap.keySet().forEach(key -> {
            DataSource ds = dataSourceCreator.createBasicDataSource(dynamicDataSourceProperties.getDatasource().get(key));
            if (dynamicDataSourceProperties.getPrimary().equals(key)) {
                dynamicDataSource.setDefault(ds);
            } else {
                dynamicDataSource.add(key, ds);
            }
        });
        return dynamicDataSource;
    }
}
